package com.easychat.controller;

import com.easychat.annotation.GlobalInterceptor;
import com.easychat.config.AppConfig;
import com.easychat.entity.constants.Constants;
import com.easychat.entity.enums.AppUpdateFileTypeEnum;
import com.easychat.entity.po.AppUpdate;
import com.easychat.entity.vo.ResponseVO;
import com.easychat.entity.vo.appupdate.response.AppUpdateVO;
import com.easychat.service.AppUpdateService;
import com.easychat.utils.CopyTools;
import com.easychat.utils.StringTools;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;

/**
 * @Author: yudaxian
 * @Description: 检测更新
 * @DateTime: 2024/8/17 10:20
 **/
@RestController
@RequestMapping("/update")
public class UpdateController extends ABaseController {

    @Resource
    private AppUpdateService appUpdateService;

    @Resource
    private AppConfig appConfig;

    @GlobalInterceptor
    @RequestMapping("/checkVersion")
    public ResponseVO checkVersion(String appVersion, String userId) {
        if (StringTools.isEmpty(appVersion)) {
            return getSuccessResponseVO(null);
        }
        AppUpdate appUpdate = appUpdateService.selectLatestVersion(appVersion, userId);
        if (null == appUpdate) {
            return getSuccessResponseVO(null);
        }
        AppUpdateVO vo = CopyTools.copy(appUpdate, AppUpdateVO.class);
        if (appUpdate.getFileType().equals(AppUpdateFileTypeEnum.LOCAL.getType())) {
            File file = new File(appConfig.getProjectFolder() + Constants.APP_UPDATE_FOLDE + appUpdate.getId() + Constants.APP_EXE_SUFFIX);
            vo.setSize(file.length());
        } else {
            vo.setSize(0L);
        }
        vo.setUpdateList(Arrays.asList(appUpdate.getUpdateDescArray()));
        vo.setFileName(Constants.APP_NAME + appUpdate.getVersion() + Constants.APP_EXE_SUFFIX);

        return getSuccessResponseVO(appUpdate);
    }

}
